import os
from datetime import timedelta

import django
from pathlib import Path

from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import make_password
from django.utils import timezone  # 新增时间模块
from dotenv import load_dotenv

# 先配置Django环境再导入模型
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ctbloge.settings")
django.setup()

# 必须在django.setup()之后导入模型
from ctbloge.apps.accounts.models import UserProfile
from ctbloge.apps.blog.models import Menu, SiteInfo, FriendLink, OauthConfig, Announcement, Carousel
from ctbloge.apps.resources.models import Resource,FavSite,Tool
from ctbloge.apps.schedulers.models import ScheduledTask
from ctbloge.apps.cms.models import Category, Topic
from ctbloge.scripts.config_data import *

# 设置项目根目录
BASE_DIR = Path(__file__).resolve().parent.parent
# 加载环境变量
load_dotenv(os.path.join(BASE_DIR, '.env'))

# 获取环境变量
username = os.getenv('ADMIN_USERNAME')
email = os.getenv('ADMIN_EMAIL')
password = os.getenv('ADMIN_PASSWORD')

blog_name = os.getenv('SITE_NAME')  # 网站名称
blog_title = os.getenv('SITE_TITLE')  # 网站标题
blog_description = os.getenv('SITE_DESC')  # 网站描述
blog_keywords = os.getenv('SITE_KEYWORDS')  # 网站关键字
blog_url = os.getenv('HOST_URL')
blog_icp = os.getenv('SITE_ICP')  # 网站备案号
blog_public_record = os.getenv('SITE_PUBLIC_RECORD')  # 网站公安备案号
blog_copyright = os.getenv('SITE_COPYRIGHT')  # 版权信息

User = get_user_model()
# 创建菜单结构
def create_menus():# 创建菜单结构
    print("Creating menus...")
    current_time = timezone.now()  # 统一时间
    menus = config_default_menus()
    for mid, pid, name, url, icon, rank in menus:
        parent = Menu.objects.filter(id=pid).first() if pid else None  # 使用更安全的查询方式
        Menu.objects.update_or_create(
            id=mid,
            defaults={
                'rank': rank,
                'name': name,
                'url': url,
                'icon': icon,
                'is_show': True,
                'parent': parent,
                'created_date': current_time,  # 添加时间字段
                'modified_date': current_time,
            }
        )
#创建管理员用户
def create_admin_user():# 创建管理员用户
    print("Creating admin user...")
    UserProfile.objects.update_or_create(
        username=username,
        defaults={
            'id': 1,
            'password': make_password(password),
            'is_superuser': True,
            'email': email,
            'nickname': '管理员',
            'qq_qrcode': 'default/auth/qq_qrcode.jpg',
            'wechat_qrcode': 'default/auth/wechat_qrcode.jpg',
            'wechat_gzh_qrcode': 'default/auth/wechat_gzh_qrcode.jpg',
            'avatar': 'default/avatar/avatar.png',
            'bio': '这个人很懒，什么都没留下！',
            'is_staff': True,
            'is_active': True,
            'rank': 0,
            'identity': 'admin',
            'date_joined': timezone.now(),  # 添加必填字段
            'last_login': timezone.now()
        }
    )
# 创建基本定时任务
def create_scheduler_tasks():
    print("Creating scheduler tasks...")
    #新建两个定时任务，定时备份数据库
    tasks = config_default_tasks()
    for task in tasks:
        ScheduledTask.objects.update_or_create(
            name=task['name'],
            defaults={
                'task_function': task['task_function'],
                'schedule_type': task['schedule_type'],
                'cron': task['cron'],
                'is_active': task['is_active'],  # 启用任务
                'start_time': timezone.now() + timedelta(seconds=120),  # 延迟120秒执行
            }
        )

#创建文章基本数据
def create_category_topic_data():
    print("Creating category/topic data...")
    # 创建分类的函数
    categories_data = config_categories()

    for data in categories_data:
        parent_name = data.get('parent')
        parent = None

        if parent_name and parent_name != '':  # 如果有父分类名称
            parent = Category.objects.filter(name=parent_name).first()
            if not parent:
                print(f"警告: 父分类 '{parent_name}' 不存在，跳过创建子分类 '{data['name']}'")
                continue

        # 创建或更新分类
        Category.objects.update_or_create(
            name=data['name'],
            slug=data['slug'],
            defaults={
                'cover': data['cover'],
                'description': data['description'],
                'rank': data['rank'],
                'parent': parent,
            }
        )

    Topic.objects.update_or_create(
        name='默认话题',
        defaults={
            'description': '这个只是默认话题，没有其他内容！',
        }
    )
 #创建资源基本数据
def create_resource_data():
    print("Creating resource data...")
    from ctbloge.apps.cms.models import Category
    # 导入资源数据
    downloads=config_resource_downloads()
    navigations=config_resource_navsites()
    tools=config_resource_tools()
    for download in downloads:
        Resource.objects.update_or_create(
            title=download['title'],
            defaults={
                'desc': download['desc'],
                'content': download['content'],
                'file': download['file'],
                'file_type': download['file_type'],
                'author': UserProfile.objects.get(is_superuser=True),
                'category': Category.objects.get(name='下载资源'),
                'is_public': True,
            }
        )
    for nav in navigations:
        FavSite.objects.update_or_create(
            name=nav['name'],
            defaults={
                'desc': nav['desc'],
                'site_url': nav['site_url'],
                'icon': nav['icon'],
                'image': nav['image'],
                'user': UserProfile.objects.get(is_superuser=True),
                'category': Category.objects.get(name=nav['category'], parent__name='网址导航'),
                'is_public': True,
            }
        )
    for tool in tools:
        Tool.objects.update_or_create(
            name=tool['name'],
            defaults={
                'desc': tool['desc'],
                'link': tool['link'],
                'route': tool['route'],
                'category': Category.objects.get(name=tool['category'], parent__name='工具推荐'),
                'is_official': tool['is_official'],
            }
        )
# 创建站点基本数据
def create_site_data():
    print("Creating oauth config...")
    oauth_list = [
        {
            'name': 'qq',
            'app_id': os.getenv('QQ_CLIENT_ID'),
            'app_key': os.getenv('QQ_CLIENT_SECRET'),
            'redirect_uri': settings.VITE_REDIRECT_URI + 'qq',
            'is_enable': True,
        },
        {
            'name': 'weibo',
            'app_id': os.getenv('WEIBO_CLIENT_ID'),
            'app_key': os.getenv('WEIBO_CLIENT_SECRET'),
            'redirect_uri': settings.VITE_REDIRECT_URI  + 'weibo',
            'is_enable': True,
        },
        {
            'name': 'github',
            'app_id': os.getenv('GITHUB_CLIENT_ID'),
            'app_key': os.getenv('GITHUB_CLIENT_SECRET'),
            'redirect_uri': settings.VITE_REDIRECT_URI + 'github',
            'is_enable': True,
        },
        {
            'name': 'gitee',
            'app_id': os.getenv('GITEE_CLIENT_ID'),
            'app_key': os.getenv('GITEE_CLIENT_SECRET'),
            'redirect_uri': settings.VITE_REDIRECT_URI + 'gitee',
            'is_enable': True,
        },
    ]
    # 创建第三方登录配置
    for oauth in oauth_list:
        OauthConfig.objects.update_or_create(
            name=oauth['name'],
            defaults={
                'app_id': oauth['app_id'],
                'app_key': oauth['app_key'],
                'redirect_uri': oauth['redirect_uri'],
                'is_enable': oauth['is_enable'],
            }
        )
    print("Creating site data...")
    # 创建站点信息
    SiteInfo.objects.update_or_create(
        id=1,
        defaults={
            'name': blog_name,
            'title': blog_title,
            'keywords': blog_keywords,
            'description': blog_description,
            'domain': blog_url,
            'icp': blog_icp,
            'public_record': blog_public_record,
            'copyright': blog_copyright,
            'logo': 'default/blog/logo.png',
            'icon': 'default/blog/icon.png',
            'background': 'default/blog/background.jpg',
            'is_reward': True,
            'is_oauth': False,
            'wechat_reward_qrcode': 'default/blog/wechat_reward_qrcode.jpg',
            'alipay_reward_qrcode': 'default/blog/alipay_reward_qrcode.jpg',
            'bloguser': UserProfile.objects.get(is_superuser=True),
            'created_date': timezone.now(),  # 添加时间字段
        })
    # 绑定第三方登录配置
    site_info = SiteInfo.objects.get(id=1)
    oauth_configs = [OauthConfig.objects.filter(name=oauth['name']).first() for oauth in oauth_list]
    # 过滤掉可能为 None 的对象
    oauth_configs = [oauth for oauth in oauth_configs if oauth is not None]
    site_info.oauth_list.set(oauth_configs)
    site_info.save()
    print("Creating friend links...")
    # 创建友情链接
    links = config_links()
    for link in links:
        FriendLink.objects.update_or_create(
            name=link['name'],
            defaults={
                'url': link['url'],
                'logo_url': link['logo_url'],
                'description': link['description'],
                'created_date': timezone.now(),  # 添加时间字段
            }
        )
    print("Creating announcements...")
    # 创建默认公告
    announcement = config_default_announcements()
    for anno in announcement:
        Announcement.objects.update_or_create(
            title=anno['title'],
            defaults={
                'content': anno['content'],
                'is_jump': anno['is_jump'],
                'jump_url': anno['jump_url'],
                'is_system': anno['is_system'],
                'created_date': timezone.now(),  # 添加时间字段
            }
        )
    print("Creating carousels...")
    # 创建轮播图
    carousels = config_default_carousel()
    for carousel in carousels:
        Carousel.objects.update_or_create(
            name=carousel['name'],
            defaults={
                'image': carousel['image'],
                'url': carousel['url'],
                'is_enable_url': carousel['is_enable_url'],
                'is_show': carousel['is_show'],
                'created_date': timezone.now(),  # 添加时间字段
            }
        )
#汇总函数
def create_blog_data():
    print("Creating database...")
    # 创建管理员用户
    create_admin_user()
    # 创建菜单结构
    create_menus()
    # 创建分类/话题数据
    create_category_topic_data()
    # 创建资源基本数据
    create_resource_data()
    # 创建站点基本数据
    create_site_data()
    # 创建定时任务
    create_scheduler_tasks()
    print("Done!")
if __name__ == '__main__':
    try:
        create_blog_data()
    except Exception as e:
        print(e)